using B.S.XZYData.Api.Read.Application.Command.WorkOrderReport;
using B.S.XZYData.Domain.LJC.Dto;
using B.S.XZYData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace B.S.XZYData.Api.Read.Controllers
{
    /// <summary>
    /// 工单报工关联控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class WorkOrderReportController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<WorkOrderReportController> _logger;

        public WorkOrderReportController(IMediator mediator, ILogger<WorkOrderReportController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取工单报工关联列表（分页）
        /// </summary>
        /// <param name="command">查询参数</param>
        /// <returns>分页的工单报工关联数据</returns>
        [HttpGet("list")]
        public async Task<ActionResult<ApiPageing<WorkOrderReportViewDto>>> GetWorkOrderReportList([FromQuery] GetWorkOrderReportListCommand command)
        {
            try
            {
                _logger.LogInformation($"接收到工单报工关联列表查询请求，页码：{command.Index}，每页大小：{command.Size}");
                
                var result = await _mediator.Send(command);
                
                if (result.Code == ApiEnum.Success)
                {
                    _logger.LogInformation($"工单报工关联列表查询成功，返回 {result.PageData?.Count ?? 0} 条记录");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"工单报工关联列表查询失败：{result.Msg}");
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"工单报工关联列表查询异常：{ex.Message}");
                
                return BadRequest(new ApiPageing<WorkOrderReportViewDto>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"查询失败：{ex.Message}",
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = new List<WorkOrderReportViewDto>()
                });
            }
        }

        /// <summary>
        /// 获取工单报工统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet("statistics")]
        public async Task<ActionResult<ApiResult<object>>> GetStatistics()
        {
            try
            {
                _logger.LogInformation("开始获取工单报工统计信息");
                
                // 构建查询命令获取全部数据进行统计
                var command = new GetWorkOrderReportListCommand
                {
                    Index = 1,
                    Size = int.MaxValue // 获取全部数据用于统计
                };
                
                var result = await _mediator.Send(command);
                
                if (result.Code == ApiEnum.Success && result.PageData != null)
                {
                    var items = result.PageData;
                    
                    var statistics = new
                    {
                        TotalWorkOrders = items.Count,
                        CompletedWorkOrders = items.Count(x => x.Status == "Completed"),
                        InProgressWorkOrders = items.Count(x => x.Status == "InProgress"),
                        NotStartedWorkOrders = items.Count(x => x.Status == "NotStarted"),
                        TotalPlannedQuantity = items.Sum(x => x.PlannedQuantity ?? 0),
                        TotalActualQuantity = items.Sum(x => x.ActualQuantity ?? 0),
                        TotalGoodQuantity = items.Sum(x => x.GoodQuantity),
                        TotalBadQuantity = items.Sum(x => x.BadQuantity),
                        TotalReportHours = items.Sum(x => x.ReportHours),
                        AverageGoodRate = items.Any() ? items.Average(x => 
                        {
                            var total = x.GoodQuantity + x.BadQuantity;
                            return total > 0 ? (decimal)x.GoodQuantity / total * 100 : 100;
                        }) : 0
                    };
                    
                    _logger.LogInformation("工单报工统计信息获取成功");
                    
                    return Ok(new ApiResult<object>
                    {
                        Code = ApiEnum.Success,
                        Msg = "获取统计信息成功",
                        Data = statistics
                    });
                }
                else
                {
                    _logger.LogWarning($"获取工单报工统计信息失败：{result.Msg}");
                    return BadRequest(new ApiResult<object>
                    {
                        Code = ApiEnum.Fail,
                        Msg = result.Msg ?? "获取统计信息失败",
                        Data = null
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取工单报工统计信息异常：{ex.Message}");
                
                return BadRequest(new ApiResult<object>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"获取统计信息失败：{ex.Message}",
                    Data = null
                });
            }
        }
    }
}
